﻿using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Data;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
using System.Text;
using CommDll;
using System.Xml.Linq;
using System.Xml;
using System.Drawing;
using System.ComponentModel;
using DevComponents.DotNetBar.Controls;
namespace InstitutionAssitant
{
    /// <summary>
    /// ClassName:frmQuery_EnterpriseCodeCheck
    /// Version:1.0
    /// Date:2019-06-23
    /// Author:seanouyang
    /// </summary>
    /// <remarks>
    /// 本类是一WinForm 窗体,本窗体主要为实现企业对码(先确定本地企业信息)
    /// </remarks>
    public partial class frmQuery_EnterpriseCodeCheck : DevComponents.DotNetBar.OfficeForm
    {
        #region 01 自定义属性
        public int m_nKind = 0; // 0:普通对码 1:指定对码(指定对码时用:本地订单)
        public Dictionary<string,string> m_dictInfo = new Dictionary<string,string>(); // 回传信息
        #endregion

        public frmQuery_EnterpriseCodeCheck()
        {
            InitializeComponent();
        }
  
        #region 02 自定义方法
        /// <summary>
        /// 初始化DataGridView字段显示信息
        /// </summary>
        public void _initDgvTitle()
        {
            string strInfo = "";
            string strKind = "";
            strKind = this.Name+"0";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "ID-序号,Code-HIS配企编码,Name-HIS配企名称,SupplierCode-配企编码,SupplierName-配企名称,Linkman-业务员,CheckCodeTime-对码时间";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "ID,Code,Name,SupplierCode,SupplierName,Linkman,CheckCodeTime";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            strInfo = "ID,Code,Name,SupplierCode,SupplierName,Linkman,CheckCodeTime";
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "0,100,300,100,300,80,200";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);

            strKind = this.Name + "1";
            // 存在时不再处理
            if (AppConfig.m_dictFieldName.ContainsKey(strKind))
            {
                return;
            }
            strInfo = "Code-配企编码,Name-配企名称,Linkman-业务员";
            AppConfig.m_dictFieldName.Add(strKind, strInfo);
            strInfo = "Code,Name,Linkman";
            AppConfig.m_dictFieldSql.Add(strKind, strInfo);
            strInfo = "Code,Name,Linkman";
            AppConfig.m_dictField0.Add(strKind, strInfo);
            strInfo = "150,200,200";
            AppConfig.m_dictFieldWidth0.Add(strKind, strInfo);
            // 设置值
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_Field", strKind), AppConfig.m_dictField0[strKind]).Trim();
            AppConfig.m_dictField.Add(strKind, strInfo);
            strInfo = AppConfig.m_iniSetup._readValue("Common", string.Format("{0}_FieldWidth", strKind), AppConfig.m_dictFieldWidth0[strKind]).Trim();
            AppConfig.m_dictFieldWidth.Add(strKind, strInfo);
        }

        /// <summary>
        /// 查询信息
        /// </summary>
        private void _queryCustomer0()
        {
            string strWhere = "";
            string strTemp = "";
            try
            {
                // 01 取条件
                // 0101 通用条件
                strTemp = txtWhere0.Text.Trim();
                if (!strTemp.Equals("") && (cbWhere01.Checked || cbWhere02.Checked))
                {
                    strTemp = "";
                    if (cbWhere01.Checked)
                    {
                        strTemp = (strTemp.Equals("") ? "" : " or ") + string.Format("(Code like '%{0}%' or SupplierCode like '%{0}%')", txtWhere0.Text.Trim());
                    }
                    if (cbWhere02.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("(Name like '%{0}%' or SupplierName like '%{0}%')", txtWhere0.Text.Trim());
                    }
                    strWhere = (strWhere.Equals("") ? "" : " and ") + string.Format("({0})", strTemp);
                }
                // 0102 对码状态
                //strTemp = "";
                //if (cbState0.Checked || cbState1.Checked || cbState.Checked) {
                //    if (cbState0.Checked)
                //    {
                //        strTemp = (strTemp.Equals("") ? "" : " or ") + string.Format("CheckCodeStatus = {0} ", 0);
                //    }
                //    if (cbState1.Checked)
                //    {
                //        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("CheckCodeStatus = {0} ", 1);
                //    }
                //    if (cbState.Checked)
                //    {
                //        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("CheckCodeStatus = {0} ", -1);
                //    }
                //    strWhere = (strWhere.Equals("") ? "" : " and ") + string.Format("({0})", strTemp);
                //}
                strWhere = (strWhere.Equals("") ? "" : " where ") + string.Format("{0}", strWhere);

                // 03 取数据
                string strSql = string.Format("SELECT top 1000 {0} FROM V_SupplierCheck {{0}} order by ID", AppConfig.m_dictFieldSql[this.Name + "0"]); 
                strSql = string.Format(strSql, strWhere);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 04 显示数据
                    // 0401 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name + "0"]);
                    // 0402 显示数据
                    CommFun._showDataGridView0(dgv0, dt, AppConfig.m_dictFieldWidth[this.Name + "0"], AppConfig.m_dictFieldName[this.Name + "0"]);
                    // 0403 显示明细数据
                    dgv0_CellClick(dgv0, new DataGridViewCellEventArgs(dgv0.Columns["Name"].Index, 0));
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgv0.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }                    
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }

            // 05 清除匹配数据
            if (dgv0.Rows.Count < 1) {
                _clearCustomerInfo1();
            }            
        }

        /// <summary>
        /// 查询匹配信息
        /// </summary>
        private void _queryCustomer1()
        {
            try
            {
                // 01 条件1
                string strWhere = "", strTemp = "";
                string strTemp1 = txtWhere1.Text.Trim();
                if (!strTemp1.Equals("") && (cbWhere11.Checked || cbWhere12.Checked))
                {
                    if (cbWhere11.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Code like '%{0}%' ", strTemp1);
                    }
                    if (cbWhere12.Checked)
                    {
                        strTemp += (strTemp.Equals("") ? "" : " or ") + string.Format("Name like '%{0}%' ", strTemp1);
                    }
                    strWhere = string.Format(" Where  ({0})", strTemp);
                }
                else
                {
                    //CommFun._messageBoxShow("查询条件不能为空!");
                    //return;
                }     

                // 03 取数据
                string strSql = "select * from (SELECT SupplierCode as Code,SupplierName as Name,'' as Linkman FROM T_DeliveryDetail group by SupplierCode,SupplierName) A {0} order by Code";
                if (cbIsBySalesman.Checked) {
                    strSql = "select * from (SELECT SupplierCode as Code,SupplierName as Name,Salesman as Linkman FROM T_DeliveryDetail group by SupplierCode,SupplierName,Salesman) A {0} order by Code";
                }
                strSql = string.Format(strSql, strWhere);
                DataTable dt = DbHelper.DBAccess[0]._openSql_Dt(strSql);
                if (dt != null && dt.Rows.Count > 0)
                {
                    // 04 显示数据
                    // 0401 调整字段顺序
                    CommFun._dataTableFieldMove(dt, AppConfig.m_dictField[this.Name + "1"]);
                    // 0402 显示数据
                    CommFun._showDataGridView0(dgv1, dt, AppConfig.m_dictFieldWidth[this.Name + "1"], AppConfig.m_dictFieldName[this.Name + "1"]);
                }
                else
                {
                    // 清除数据
                    DataTable dtTemp = (DataTable)dgv1.DataSource;
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        dtTemp.Rows.Clear();
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }

        /// <summary>
        /// 清除匹配信息
        /// </summary>
        private void _clearCustomerInfo1()
        {
            txtWhere1.Text = "";
            if (dgv1.Rows.Count > 0)
            {
                ((DataTable)dgv1.DataSource).Rows.Clear();
            }
        }

        /// <summary>
        /// 药品对码
        /// </summary>
        private void _checkCode()
        {
            if (dgv0.CurrentRow == null)
            {
                CommFun._messageBoxShow("请先确定HIS数据！");
                return;
            }
            try
            {
                frmSupplierCodeCheck frm = new frmSupplierCodeCheck();
                // 联系人处理
                // 01 取联系人(当新的配企与原配企不相同时，去除原配企联系人)
                if (!string.IsNullOrWhiteSpace(ModelSupplierCodeCheck.strSupplierCode)&&!ModelSupplierCodeCheck.strSupplierCode.Equals(ModelSupplierCodeCheck.strCode1))
                {
                    ModelSupplierCodeCheck.strLinkman0 = "";
                }
                
                // 02 当原配企有联系人时加入新的联系人
                if (!string.IsNullOrWhiteSpace(ModelSupplierCodeCheck.strLinkman1))
                {
                    if (!string.Format(",{0},", ModelSupplierCodeCheck.strLinkman0).Contains(string.Format(",{0},", ModelSupplierCodeCheck.strLinkman1)))
                    {
                        ModelSupplierCodeCheck.strLinkman0 += ((string.IsNullOrWhiteSpace(ModelSupplierCodeCheck.strLinkman0)) ? "" : ",") + ModelSupplierCodeCheck.strLinkman1;
                    }
                }
                
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    if (m_nKind == 1)
                    {
                        // 需返回信息
                        m_dictInfo.Add("SupplierCode", ModelSupplierCodeCheck.strCode1);
                        m_dictInfo.Add("SupplierName", ModelSupplierCodeCheck.strName1);
                        DialogResult = DialogResult.OK;
                    }
                    else {
                        // 更新数据
                        dgv0.Rows[dgv0.CurrentRow.Index].Cells["Code"].Value = ModelSupplierCodeCheck.strCode1;
                        dgv0.Rows[dgv0.CurrentRow.Index].Cells["Name"].Value = ModelSupplierCodeCheck.strName1;
                        dgv0.Rows[dgv0.CurrentRow.Index].Cells["Linkman"].Value = ModelSupplierCodeCheck.strLinkman0;
                        dgv0.Rows[dgv0.CurrentRow.Index].Cells["CheckCodeTime"].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                        ModelSupplierCodeCheck.strSupplierCode = ModelSupplierCodeCheck.strCode1; 
                    }
                }
            }
            catch (Exception ex)
            {
                CommFun._messageBoxShow(ex.Message);
                return;
            }
        }
        #endregion

        #region 03 窗体相关事件方法
        private void frmQuery_EnterpriseCodeCheck_Load(object sender, EventArgs e)
        {
            timerInit.Enabled = true;
            dgv0.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
            dgv1.Anchor = (System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Top));
        }
        private void timerInit_Tick(object sender, EventArgs e)
        {
            timerInit.Enabled = false;
            // 初始化DataGridView
            _initDgvTitle();
            // 指定配企信息对码使用
            if (m_nKind == 1)
            {
                // 赋默认值
                gbInfo0.Text = "HIS配企信息";
                txtWhere0.Text = m_dictInfo["SupplierCode"];
                txtWhere0.ReadOnly = true;
                cbWhere01.Checked = true;
                cbWhere01.Enabled = false;
                cbWhere02.Checked = false;
                cbWhere02.Enabled = false;
                //cbState.Enabled = false;
                //cbState0.Enabled = false;
                //cbState1.Enabled = false;
                // 取数据
                btnQuery0_Click(null, null);
            }
        }

        private void btnQuery0_Click(object sender, EventArgs e)
        {
            _queryCustomer0();
        }
        
        private void btnQuery1_Click(object sender, EventArgs e)
        {
            _queryCustomer1();
        }
        private void txtWhere0_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery0_Click(null, null);
            }
        }

        private void txtWhere1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnQuery1_Click(null, null);
            }
        }        
        #endregion

        #region 04 DataGridView 事件方法

        private void dataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            // 标题排序
            CommFun._dgvColumnHeaderSort(sender, e);
        }        

        private void dgv0_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 取匹配数据
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }

            DataGridView dgv = (DataGridView)sender;
            // 取His数据
            ModelSupplierCodeCheck.strID0 = dgv.Rows[e.RowIndex].Cells["ID"].Value.ToString();
            ModelSupplierCodeCheck.strCode0 = dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString();
            ModelSupplierCodeCheck.strName0 = dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString();
            ModelSupplierCodeCheck.strLinkman0 = dgv.Rows[e.RowIndex].Cells["Linkman"].Value.ToString();
            ModelSupplierCodeCheck.strSupplierCode = dgv.Rows[e.RowIndex].Cells["SupplierCode"].Value.ToString();
            
            // 按指定列名信息查询数据
            string strTemp = dgv.Columns[e.ColumnIndex].Name;
            cbWhere11.Checked = false;
            cbWhere12.Checked = false;
            if ("Code,SupplierCode,Name,SupplierName".Contains(strTemp))
            {
                switch (strTemp)
                {
                    case "Code":
                    case "SupplierCode":
                        cbWhere11.Checked = true;
                        break;
                    case "Name":
                    case "SupplierName":
                        cbWhere12.Checked = true;
                        break;
                }
                txtWhere1.Text = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                btnQuery1_Click(null, null);
            }
            else
            {
                _clearCustomerInfo1();
            }
        }

        private void dataGridViewX1_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 改变行颜色
            CommFun._dgvRowEnter(sender, e);
        }
        private void dataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // 双击对码操作
            if (e.RowIndex < 0 || e.ColumnIndex < 0)
            {
                return;
            }
            DataGridView dgv = (DataGridView)sender;
            switch (dgv.Name)
            {
                case "dgv0":
                    // 对码操作:设置“暂不对码”
                    if (m_nKind != 1)
                    {
                        if (CommFun._messageBoxShow("确认设置成【暂不对码】？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
                        {
                            try
                            {
                                ModelSupplierCodeCheck.strCode1 = "暂不对码";
                                ModelSupplierCodeCheck.strName1 = "";
                                ModelSupplierCodeCheck._saveInfo();
                                // 更新数据
                                dgv.CurrentRow.Cells["Code"].Value = ModelSupplierCodeCheck.strCode1;
                                dgv.CurrentRow.Cells["Name"].Value = ModelSupplierCodeCheck.strName1;
                                //dgv.CurrentRow.Cells["Linkman"].Value = "";
                            }
                            catch (Exception ex)
                            {
                                CommFun._messageBoxShow(ex.Message);
                                return;
                            }
                        }
                    }
                    break;
                case "dgv1":
                    // 初始化匹配信息
                    ModelSupplierCodeCheck.strCode1 = dgv.Rows[e.RowIndex].Cells["Code"].Value.ToString();
                    ModelSupplierCodeCheck.strName1 = dgv.Rows[e.RowIndex].Cells["Name"].Value.ToString();
                    ModelSupplierCodeCheck.strLinkman1 = dgv.Rows[e.RowIndex].Cells["Linkman"].Value.ToString();
                    // 对码
                    _checkCode();
                    break;
            }
        }

        private void dataGridView_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 设置标题信息    
            if (e.Button == MouseButtons.Right)
            {
                DataGridView dgv = (DataGridView)sender;
                frmDataShowSetup frm = new frmDataShowSetup();
                switch (dgv.Name)
                {
                    case "dgv0":
                        frm.m_strInfoKind = this.Name + "0";
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            if (frm.m_bIsSaveWidth)
                            {
                                // 保存宽度
                                AppConfig._saveDgvWidth(dgv0, frm.m_strInfoKind);
                                CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                if (dgv0.Rows.Count > 0)
                                {
                                    btnQuery0_Click(null, null);
                                }
                            }
                        }
                        break;
                    case "dgv1":
                        frm.m_strInfoKind = this.Name + "1";
                        if (frm.ShowDialog() == DialogResult.OK)
                        {
                            if (frm.m_bIsSaveWidth)
                            {
                                // 保存宽度
                                AppConfig._saveDgvWidth(dgv1, frm.m_strInfoKind);
                                CommFun._messageBoxShow("显示宽度保存成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                            else
                            {
                                if (dgv0.Rows.Count > 0)
                                {
                                    btnQuery1_Click(null, null);
                                }
                            }
                        }
                        break;
                }
            }
        }
        #endregion
    }
}


